package com.ljb.monitorview.monitor2;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ljb.monitorview.monitor3.NotifyData3;
import com.squareup.picasso.Picasso;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新版工艺监控自定义控件
 * Created by ljb on 2017/6/16.
 */

public class MonitorView2 extends FrameLayout {
    private static final String TAG = "MonitorView";

    private int local_width;//实际控件的宽
    private int local_height;//实际控件的高
    private Context c;//上下文
    private ImageView bg;//背景
    private Map<String, View> viewMap = new HashMap<>();//模拟量和数字量的View对象
    public final long TIME_INTERRUPT = 60 * 3;//数据断开状态阈值

    private ConfigBean2.Configuration mConfig;//配置信息
    public List<ConfigBean2.Pic> pic;//动态数据
    public List<ConfigBean2.Content> content;//固定文本


    public MonitorView2(@NonNull Context context) {
        this(context, null);
    }

    public MonitorView2(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MonitorView2(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        c = context;
        setWillNotDraw(false);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (oldw == oldh && w > h) {
            //获取控件的大小
            this.local_width = w;
            this.local_height = h;
            Log.e(TAG, "onSizeChanged: MonitorView控件的宽:" + w + ";高:" + h);
        }
    }

    //设置背景
    private void initBg() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        params.setMargins(0, 0, 0, 0);
        LinearLayout layout = new LinearLayout(c);
        bg = new ImageView(c);
        bg.setLayoutParams(params);
        bg.setScaleType(ImageView.ScaleType.FIT_XY);
        layout.addView(bg);
        addView(layout);

        String bgUrl = mConfig.preUrl + mConfig.bgUrl;
        Log.e(TAG, "initBg: 背景URL:" + bgUrl);
        Picasso.with(c).load(utf8Togb2312(bgUrl)).into(bg);
        Log.e(TAG, "initBg: 设置背景完毕");
    }

    //utf8转gbk的工具
    private String utf8Togb2312(String str) {
        String data = "";
        try {
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c + "".getBytes().length > 1 && c != ':' && c != '/') {
                    data = data + java.net.URLEncoder.encode(c + "", "utf-8");
                } else {
                    data = data + c;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            Log.d(TAG, "utf8Togb2312: 转码后的地址为:" + data);
        }
        return data;
    }

    //增加模拟量控件(动态变化的数字)
    private void addAningog(ConfigBean2.Pic pic) {
        //设置模拟量的位置
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        // TODO: 2017/6/20 模拟量位置适配在此处处理
        int l = (int) (pic.monitorLocationX / mConfig.designX * local_width);
        int t = (int) (pic.monitorLocationY / mConfig.designY * local_height);
        params.setMargins(l, t, 0, 0);
        LinearLayout layout = new LinearLayout(c);

        TextView textView = new TextView(c);
        textView.setLayoutParams(params);
        textView.setTextSize(mConfig.dataSize);
        textView.setTextColor(Color.parseColor(mConfig.dataColor));
        textView.setText("$$");

        layout.addView(textView);
        addView(layout);
        viewMap.put(pic.monitorFieldCode, textView);
        Log.e(TAG, "addAningog: 增加模拟量完毕 " + pic.monitorFieldCode);
    }


    //增加数字量控件(小圆图)
    private void addDigiting(ConfigBean2.Pic pic) {
        //设置数字量的位置
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) (pic.monitorLocationImgWidth / mConfig.designX * local_width), (int) (pic.monitorLocationImgHeight / mConfig.designY * local_height));
        // TODO: 2017/6/20 数字量位置适配在此处处理
        int l = (int) (pic.monitorLocationX / mConfig.designX * local_width);
        int t = (int) (pic.monitorLocationY / mConfig.designY * local_height);

        params.setMargins(l, t, 0, 0);

        ImageView imageView = new ImageView(c);
        imageView.setLayoutParams(params);
        Picasso.with(c).load(utf8Togb2312(mConfig.preUrl + "common/point-r.png")).into(imageView);

        LinearLayout layout = new LinearLayout(c);
        layout.addView(imageView);
        addView(layout);
        viewMap.put(pic.monitorFieldCode, imageView);
        Log.e(TAG, "addAningog: 增加数字量完毕 " + pic.monitorFieldCode);
    }

    //增加固定文本显示
    private void addConstantData(ConfigBean2.Content content) {
        //设置固定为本的位置
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        // TODO: 2017/6/20 固定文本位置适配在此处处理
//        int l = (int) (pos.left / 100 * local_width + mConfig.textX * (1 - pos.left / 100));
//        int t = (int) (pos.top / 100 * local_height + mConfig.textY * (1 - pos.left / 100));

        int l = (int) (content.monitorLocationX / mConfig.designX * local_width);
        int t = (int) (content.monitorLocationY / mConfig.designY * local_height);
        params.setMargins(l, t, 0, 0);
        LinearLayout layout = new LinearLayout(c);

        TextView textView = new TextView(c);
        textView.setLayoutParams(params);
        textView.setTextSize(mConfig.textSize);
        textView.setText(content.monitorLocationName);
        textView.setTextColor(Color.parseColor(mConfig.textColor));

        layout.addView(textView);
        addView(layout);
        Log.e(TAG, "addAningog: 增加固定文本完毕");
    }
/***********************************************************************************************/
    /**
     * 为控件添加数据
     */
    private void setData() {
        for (int i = 0; i < pic.size(); i++) {
            ConfigBean2.Pic pic = this.pic.get(i);
            switch (pic.monitorFieldType) {
                case 0://模拟量
//                    addAningog(pic);
                    break;
                case 1://数字量
                    addDigiting(pic);
                    break;
//                case "zoneFour"://文本
//                    addConstantData(pic, pos.get(i));
//                    break;
//                case "zoneThree"://可控变量
//                    break;
            }
        }
//        for (int i = 0; i < content.size(); i++) {
//            ConfigBean2.Content content = this.content.get(i);
//            addConstantData(content);
//        }
    }

    /**
     * 设置配置信息
     *
     * @param config
     */
    public void setConfig(ConfigBean2 config) {
        mConfig = config.configuration;
        pic = config.pic;
        content = config.content;
        initBg();
        setData();
    }

    /**
     * 清空控件上的所有点的数据
     */
    public void clearData() {
        removeAllViews();
        pic.clear();
        content.clear();
        viewMap.clear();
    }

    /**
     * 刷新动态数据
     *
     * @param notifyData3
     */
    public void notifyData(NotifyData3 notifyData3) {
        judgeDataStauts(notifyData3);
    }

    /*******************************************************************************************/


    /**
     * 判断当前数据连接状态,如果数据库中最新数据的入库时间戳和当前时间戳做差值,
     * 超过断开阈值则判断为数据断开状态
     */
    private void judgeDataStauts(NotifyData3 notifyData3) {
        long time_data = notifyData3.time;
        long time_now = System.currentTimeMillis() / 1000;
        if (time_now - time_data > TIME_INTERRUPT) {//数据处于断开状态
            Log.e(TAG, "judgeDataSuts: 当前数据状态为: 断开状态");
            switch (notifyData3.interruptmode) {
                case 1://默认显示数据库中的最后一条数据
                    notifyDataInterrupt1(notifyData3.list);//刷新断开状态的数据,断开模式为1
                    break;
                case 2://所有的模拟量显示为0,数字量显示为错误
                    notifyDataInterrupt2(notifyData3.list);//刷新断开状态的数据,断开模式为2
                    break;
                case 3://所有的模拟量显示为空,数字量显示为空
                    notifyDataInterrupt3(notifyData3.list);//刷新断开状态的数据,断开模式为3
                    break;
            }
        } else {//数据处于连接状态
            Log.e(TAG, "judgeDataSuts: 当前数据状态为: 连接状态");
            notifyDataNormal(notifyData3.list);
        }
    }

    //模式3的断开状态
    private void notifyDataInterrupt3(List<NotifyData3.List> lists) {
        for (int i = 0; i < lists.size(); i++) {
            NotifyData3.List list = lists.get(i);
            String key = list.name;
            if (!viewMap.containsKey(key)) {//判断是否包含key
                continue;
            }
            View view = viewMap.get(key);
            String value = list.value;
            if (view instanceof TextView) {//模拟量
                notifyAningogNormal((TextView) view, "  ");
                Log.e(TAG, "notifyDataNormal: 刷新模拟量 " + key);
            } else if (view instanceof ImageView) {//数字量
                notifyDigitingInterrupt3(list, (ImageView) view, value);
                Log.e(TAG, "notifyDataNormal: 刷新数字量 " + key);
            }
        }
    }

    //模式3的数字量断开状态,隐藏数字量
    private void notifyDigitingInterrupt3(NotifyData3.List list, ImageView view, String value) {
        String imgPath = list.imgPath;
        //复合状态
        if (value.contains("word")) {
            String word = value.replaceAll("word", "");
            if (word.isEmpty()) {
                return;
            }
            String imgPathSub = imgPath.substring(imgPath.indexOf("-") + 1, imgPath.indexOf("."));
            imgPath = imgPath.replaceAll("-" + imgPathSub, "-" + word);
        } else {//单一状态
            switch (value) {
                case "0"://停止状态
                case "1"://运行状态
                case "2"://错误状态
                case "4"://开到关,关到开的中间状态
                case "3"://隐藏状态
                    view.setVisibility(View.INVISIBLE);//隐藏数字量
                    return;
            }
        }
        //加载图片
        view.setVisibility(View.VISIBLE);
        Picasso.with(c).load(utf8Togb2312(mConfig.preUrl + imgPath)).into(view);
    }

    //模式2的断开状态
    private void notifyDataInterrupt2(List<NotifyData3.List> lists) {
        for (int i = 0; i < lists.size(); i++) {
            NotifyData3.List list = lists.get(i);
            String key = list.name;
            if (!viewMap.containsKey(key)) {//判断是否包含key
                continue;
            }
            View view = viewMap.get(key);
            String value = list.value;
            if (view instanceof TextView) {//模拟量
                notifyAningogNormal((TextView) view, "0");
                Log.e(TAG, "notifyDataNormal: 刷新模拟量 " + key);

            } else if (view instanceof ImageView) {//数字量
                notifyDigitingInterrupt2(list, (ImageView) view, value);
                Log.e(TAG, "notifyDataNormal: 刷新数字量 " + key);
            }
        }
    }

    //模式1的断开状态
    private void notifyDataInterrupt1(List<NotifyData3.List> list) {
        notifyDataNormal(list);
    }

    //模式2的数字量的断开状态,所有数字量显示停止状态
    private void notifyDigitingInterrupt2(NotifyData3.List list, ImageView view, String value) {
        String imgPath = list.imgPath;
        //复合状态
        if (value.contains("word")) {
            String word = value.replaceAll("word", "");
            if (word.isEmpty()) {
                return;
            }
            String imgPathSub = imgPath.substring(imgPath.indexOf("-") + 1, imgPath.indexOf("."));
            imgPath = imgPath.replaceAll("-" + imgPathSub, "-" + word);
        } else {//单一状态
            switch (value) {
                case "0"://停止状态
                case "1"://运行状态
                case "2"://错误状态
                case "4"://开到关,关到开的中间状态
                    imgPath = imgPath.replaceAll("-s", "-f");
                    imgPath = imgPath.replaceAll("-r", "-f");
                    imgPath = imgPath.replaceAll("-b", "-f");
                    break;
                case "3"://隐藏状态
                    view.setVisibility(View.INVISIBLE);
                    return;
            }
        }
        //加载图片
        view.setVisibility(View.VISIBLE);
        Picasso.with(c).load(utf8Togb2312(mConfig.preUrl + imgPath)).into(view);
    }

    //刷新正常状态的数据
    private void notifyDataNormal(List<NotifyData3.List> lists) {
        for (int i = 0; i < lists.size(); i++) {
            NotifyData3.List list = lists.get(i);
            String key = list.name;
            if (!viewMap.containsKey(key)) {//判断是否包含key
                continue;
            }

            View view = viewMap.get(key);
            String value = list.value;
            if (view instanceof TextView) {//模拟量
                notifyAningogNormal((TextView) view, value);
                Log.e(TAG, "notifyDataNormal: 刷新模拟量 " + key);

            } else if (view instanceof ImageView) {//数字量
                notifyDigitingNormal(list, (ImageView) view, value);
                Log.e(TAG, "notifyDataNormal: 刷新数字量 " + key);
            }
        }
    }

    //刷新模拟量
    private void notifyAningogNormal(TextView view, String value) {
        String s_;
        int index = value.indexOf('.');
        if (index > 0) {
            s_ = value.substring(0, index + 2);
        } else {
            s_ = value + ".00";
        }

    }

    //刷新数字量的状态
    private void notifyDigitingNormal(NotifyData3.List list, ImageView view, String value) {
        String imgPath = list.imgPath;
        //复合状态
        if (value.contains("word")) {
            String word = value.replaceAll("word", "");
            if (word.isEmpty()) {
                return;
            }
            String imgPathSub = imgPath.substring(imgPath.indexOf("-") + 1, imgPath.indexOf("."));
            imgPath = imgPath.replaceAll("-" + imgPathSub, "-" + word);
        } else {//单一状态
            switch (value) {
                case "0"://停止状态
                    imgPath = imgPath.replaceAll("-r", "-s");
                    imgPath = imgPath.replaceAll("-f", "-s");
                    break;
                case "1"://运行状态
                    imgPath = imgPath.replaceAll("-s", "-r");
                    imgPath = imgPath.replaceAll("-f", "-r");
                    break;
                case "2"://错误状态
                    imgPath = imgPath.replaceAll("-s", "-f");
                    imgPath = imgPath.replaceAll("-r", "-f");
                    break;
                case "3"://隐藏状态
                    view.setVisibility(View.INVISIBLE);
                    return;
                case "4"://开到关,关到开的中间状态
                    imgPath = imgPath.replaceAll("-s", "-b");
                    imgPath = imgPath.replaceAll("-r", "-b");
                    imgPath = imgPath.replaceAll("-f", "-b");
                    break;
            }
        }
        //加载图片
        view.setVisibility(View.VISIBLE);
        Picasso.with(c).load(utf8Togb2312(mConfig.preUrl + imgPath)).into(view);
    }
}






































